from flask import Blueprint, request, jsonify, session, current_app
from werkzeug.security import generate_password_hash, check_password_hash
from .models import User, Message ,Zone
from . import db
import os

bp = Blueprint('routes', __name__)

@bp.route('/check_login', methods=['GET'])
def check_login():
    return jsonify({
        "status": "success",
        "data": {
            "loggedIn": 'user_id' in session
        }
    })

@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or len(username) < 3 or len(username) > 5:
        return jsonify({'message': '用户名长度必须在3到5个字符之间'}), 400
    if not password or len(password) < 6:
        return jsonify({'message': '密码长度必须大于6位'}), 400

    if User.query.filter_by(username=username).first():
        return jsonify({'message': '用户名已存在'}), 400

    password_hash = generate_password_hash(password)
    new_user = User(username=username, password_hash=password_hash, avatar_url='/static/avatars/default.png')
    db.session.add(new_user)
    db.session.commit()

    return jsonify({'message': '注册成功'}), 200


@bp.route('/login', methods=['POST', 'OPTIONS'])
def login():
    # 处理 CORS 预检请求
    if request.method == 'OPTIONS':
        response = jsonify({'message': 'CORS 预检通过'})
        response.headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
        response.headers.add('Access-Control-Allow-Methods', 'POST, OPTIONS')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        response.headers.add('Access-Control-Allow-Credentials', 'true')
        return response

    # 正常 POST 请求处理
    try:
        data = request.get_json(force=True)
    except Exception as e:
        return jsonify({'message': '无效的 JSON 数据', 'error': str(e)}), 400

    if not data:
        return jsonify({'message': '请求体为空'}), 400

    username = data.get('username')
    password = data.get('password')

    user = User.query.filter_by(username=username).first()
    if user and check_password_hash(user.password_hash, password):
        session['user_id'] = user.id  # ✅ 设置 session
        resp = jsonify({'message': '登录成功', 'success': True})
    else:
        resp = jsonify({'message': '用户名或密码错误', 'success': False}), 401

    # 加 CORS 响应头
    if isinstance(resp, tuple):
        resp[0].headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
        resp[0].headers.add('Access-Control-Allow-Credentials', 'true')
    else:
        resp.headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
        resp.headers.add('Access-Control-Allow-Credentials', 'true')

    return resp


@bp.route('/logout', methods=['POST'])
def logout():
    session.clear()
    return jsonify({
        "status": "success",
        "data": {
            "message": "退出登录成功"
        }
    }), 200


@bp.route('/messages', methods=['POST'])
def post_message():
    if 'user_id' not in session:
        return jsonify({
    "status": "error",
    "message": "请先登录"
}), 401


    data = request.get_json()
    content = data.get('content', '').strip()
    area = data.get('area', '').strip()

    if not content or not area:
        return jsonify({'message': '内容和分区不能为空'}), 400

    message = Message(content=content, user_id=session['user_id'], area=area)
    db.session.add(message)
    db.session.commit()

    return jsonify({'message': '留言成功'}), 201


@bp.route('/messages', methods=['GET'])
def get_messages():
    area = request.args.get('area')
    if not area:
        return jsonify({ 'message': '缺少分区参数' }), 400
    messages = Message.query.filter_by(area=area).order_by(Message.created_at.desc()).all()
    result = []
    for msg in messages:
        user = User.query.get(msg.user_id)
        result.append({
            'id': msg.id,
            'username': user.username if user else '未知用户',
            'content': msg.content,
            'created_at': msg.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'likes': msg.likes
        })

    return jsonify(result), 200

@bp.route('/messages/<int:msg_id>/like', methods=['POST'])
def like_message(msg_id):
    message = Message.query.get(msg_id)
    if not message:
        return jsonify({ 'message': '留言不存在' }), 404

    message.likes += 1
    db.session.commit()
    return jsonify({ 'message': '点赞成功' }), 200

@bp.route('/messages/<int:msg_id>', methods=['DELETE'])
def delete_message(msg_id):
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    message = Message.query.get(msg_id)
    if not message:
        return jsonify({'status': 'error', 'message': '留言不存在'}), 404
    db.session.delete(message)
    db.session.commit()
    return jsonify({'status': 'success', 'message': '删除成功'}), 200

@bp.route('/update_snake_score', methods=['POST'])
def update_snake_score():
    if 'user_id' not in session:
        return jsonify({"status": "error", "message": "请先登录"}), 401

    data = request.get_json()
    score = data.get('score')

    if score is None:
        return jsonify({"status": "error", "message": "缺少分数"}), 400

    user = User.query.get(session['user_id'])

    if user.snake_score is None or score > user.snake_score:
        user.snake_score = score
        db.session.commit()

    return jsonify({
        "status": "success",
        "message": "分数已更新",
        "data": {"snake_score": user.snake_score}
    })

@bp.route('/get_snake_score', methods=['GET'])
def get_snake_score():
    if 'user_id' not in session:
        return jsonify({"status": "error", "message": "请先登录"}), 401

    user = User.query.get(session['user_id'])
    return jsonify({
        "status": "success",
        "data": {"snake_score": user.snake_score}
    })


@bp.route('/update_mario_score', methods=['POST'])
def update_mario_score():
    if 'user_id' not in session:
        return jsonify({"status": "error", "message": "请先登录"}), 401

    data = request.get_json()
    score = data.get('score')

    if score is None:
        return jsonify({"status": "error", "message": "缺少分数"}), 400

    user = User.query.get(session['user_id'])

    if user.mario_score is None or score > user.mario_score:
        user.mario_score = score
        db.session.commit()

    return jsonify({
        "status": "success",
        "message": "分数已更新",
        "data": {"mario_score": user.mario_score}
    })

@bp.route('/get_mario_score', methods=['GET'])
def get_mario_score():
    if 'user_id' not in session:
        return jsonify({"status": "error", "message": "请先登录"}), 401

    user = User.query.get(session['user_id'])
    return jsonify({
        "status": "success",
        "data": {"mario_score": user.mario_score}
    })


@bp.route('/update_plane_score', methods=['POST'])
def update_plane_score():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    data = request.get_json()
    new_score = data.get('score')

    if new_score is None or not isinstance(new_score, int):
        return jsonify({'status': 'error', 'message': '分数无效'}), 400

    user = User.query.get(session['user_id'])
    if user is None:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    if new_score > user.plane_score:
        user.plane_score = new_score
        db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '分数已更新',
        'data': {
            'plane_score': user.plane_score
        }
    }), 200

@bp.route('/get_plane_score', methods=['GET'])
def get_plane_score():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    user = User.query.get(session['user_id'])
    if user is None:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    return jsonify({
        'status': 'success',
        'data': {
            'plane_score': user.plane_score
        }
    }), 200


@bp.route('/update_two_score', methods=['POST'])
def update_two_score():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    data = request.get_json()
    new_score = data.get('score', 0)

    user = User.query.get(session['user_id'])
    if user is None:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    if new_score > user.two_score:
        user.two_score = new_score
        db.session.commit()

    return jsonify({'status': 'success', 'message': '分数已更新'}), 200

@bp.route('/get_two_score', methods=['GET'])
def get_two_score():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    user = User.query.get(session['user_id'])
    if user is None:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    return jsonify({
        'status': 'success',
        'data': {
            'two_score': user.two_score
        }
    }), 200


@bp.route('/update_eat_score', methods=['POST'])
def update_eat_score():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    data = request.get_json()
    new_score = data.get('score')

    if new_score is None or not isinstance(new_score, int):
        return jsonify({'status': 'error', 'message': '分数无效'}), 400

    user = User.query.get(session['user_id'])
    if user is None:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    if new_score > user.eat_score:
        user.eat_score = new_score
        db.session.commit()

    return jsonify({
        'status': 'success',
        'message': '分数已更新',
        'data': {
            'eat_score': user.eat_score
        }
    }), 200

@bp.route('/get_eat_score', methods=['GET'])
def get_eat_score():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '请先登录'}), 401

    user = User.query.get(session['user_id'])
    if user is None:
        return jsonify({'status': 'error', 'message': '用户不存在'}), 404

    return jsonify({
        'status': 'success',
        'data': {
            'eat_score': user.eat_score
        }
    }), 200


@bp.route('/upload_avatar', methods=['POST'])
def upload_avatar():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '未登录'}), 401

    file = request.files.get('file')
    if not file:
        return jsonify({'status': 'error', 'message': '请上传文件'}), 400

    # 获取 static/avatars 目录的绝对路径
    avatar_dir = os.path.join(current_app.root_path, 'static', 'avatars')
    os.makedirs(avatar_dir, exist_ok=True)

    filename = f"{session['user_id']}.png"
    file_path = os.path.join(avatar_dir, filename)
    file.save(file_path)

    # 设置前端可访问路径
    user = User.query.get(session['user_id'])
    user.avatar_url = f"/static/avatars/{filename}"
    db.session.commit()

    return jsonify({
        'status': 'success', 
        'data': {
            'avatar': user.avatar_url
        }
    }), 200

@bp.route('/me', methods=['GET'])
def get_me():
    if 'user_id' not in session:
        return jsonify({'status': 'error', 'message': '未登录'}), 401

    user = User.query.get(session['user_id'])

    return jsonify({
        'status': 'success',
        'data': {
            'username': user.username,
            'avatar': user.avatar_url,
            'manage': user.manage,
        }
    })

@bp.route('/top_scores', methods=['GET'])
def top_scores():
    game = request.args.get('game')
    valid_games = ['snake', 'plane', 'mario', 'eat', 'two']
    field_map = {
        'snake': User.snake_score,
        'plane': User.plane_score,
        'mario': User.mario_score,
        'eat': User.eat_score,
        'two': User.two_score
    }
    if game not in valid_games:
        return jsonify({'status': 'error', 'message': '无效的游戏类型'}), 400

    users = User.query.order_by(field_map[game].desc()).limit(10).all()
    result = [
        {
            'username': user.username,
            'score': getattr(user, f"{game}_score"),
            'avatar': user.avatar_url
        }
        for user in users
    ]
    return jsonify({'status': 'success', 'data': result}), 200

@bp.route('/users/full', methods=['GET'])
def get_full_user_info():
    # 判断是否登录
    if 'user_id' not in session:
        return jsonify({'status': 'fail', 'message': '用户未登录'}), 401

    # 查询所有用户
    users = User.query.all()
    user_list = []
    for user in users:
        user_list.append({
            'id': user.id,
            'username': user.username,
            'created_at': user.created_at,
            'updated_at': user.updated_at,
            'snake_score': user.snake_score,
            'two_score': user.two_score,
            'plane_score': user.plane_score,
            'mario_score': user.mario_score,
            'eat_score': user.eat_score,
            'avatar_url': user.avatar_url,
            'manage':user.manage,
        })

    return jsonify({'status': 'success', 'data': user_list}), 200

@bp.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    manage = data.get('manage', 0)
    if not username or not password:
        return jsonify({'status': 'fail', 'message': '用户名和密码必填'}), 400
    if User.query.filter_by(username=username).first():
        return jsonify({'status': 'fail', 'message': '用户名已存在'}), 409

    password_hash = generate_password_hash(password)
    user = User(
        username=username,
        password_hash=password_hash,
        manage=manage
    )
    db.session.add(user)
    db.session.commit()
    return jsonify({'status': 'success', 'message': '用户创建成功'})

@bp.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return jsonify({'status': 'fail', 'message': '用户不存在'}), 404

    data = request.get_json()
    user.snake_score = data.get('snake_score', user.snake_score)
    user.two_score = data.get('two_score', user.two_score)
    user.plane_score = data.get('plane_score', user.plane_score)
    user.mario_score = data.get('mario_score', user.mario_score)
    user.eat_score = data.get('eat_score', user.eat_score)
    user.avatar_url = data.get('avatar_url', user.avatar_url)
    user.manage = data.get('manage', user.manage)

    # 如需改密码
    if data.get('password'):
        user.password_hash = generate_password_hash(data['password'])

    db.session.commit()
    return jsonify({'status': 'success', 'message': '用户信息已更新'})

@bp.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return jsonify({'status': 'fail', 'message': '用户不存在'}), 404
    db.session.delete(user)
    db.session.commit()
    return jsonify({'status': 'success', 'message': '用户已删除'})


@bp.route('/zones', methods=['GET'])
def get_zones():
    zones = Zone.query.all()
    return jsonify({'data': [dict(
        key=z.key,
        title=z.title,
        desc=z.desc,
        image=z.image
    ) for z in zones]})

@bp.route('/zones', methods=['POST'])
def add_zone():
    data = request.json
    z = Zone(key=data['key'], title=data['title'], desc=data['desc'], image=data['image'])
    db.session.add(z)
    db.session.commit()
    return jsonify({'message': '创建成功'})

@bp.route('/zones/<key>', methods=['PUT'])
def edit_zone(key):
    z = Zone.query.get(key)
    data = request.json
    z.title = data['title']
    z.desc = data['desc']
    z.image = data['image']
    db.session.commit()
    return jsonify({'message': '修改成功'})

@bp.route('/zones/<key>', methods=['DELETE'])
def delete_zone(key):
    z = Zone.query.get(key)
    db.session.delete(z)
    db.session.commit()
    return jsonify({'message': '删除成功'})

@bp.route('/upload_zone_img', methods=['POST'])
def upload_zone_img():
    file = request.files['file']
    filename = secure_filename(file.filename)
    path = os.path.join('static', 'img_community', filename)
    file.save(path)
    return jsonify({'url': '/static/img_community/' + filename})